/**
 *    Copyright 2012 Geensoft S.A.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 **/
package ar.com.greensoft.neo.web.jsf.beans.admin.users;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.validation.constraints.AssertTrue;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import ar.com.greensoft.neo.dao.DaoException;
import ar.com.greensoft.neo.dao.GroupDao;
import ar.com.greensoft.neo.model.Authority;
import ar.com.greensoft.neo.model.Group;
import ar.com.greensoft.neo.model.User;
import ar.com.greensoft.neo.service.UserService;
import ar.com.greensoft.neo.util.ApplicationRoles;
import ar.com.greensoft.neo.web.jsf.beans.common.CommonViewBean;
import ar.com.greensoft.neo.web.jsf.util.JSFMenuUtil;

/**
 * @author Jorge E. Villaverde
 *
 */
@Component
@RequestScoped
@ManagedBean
public class CreateUserBean extends CommonViewBean {
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	@Autowired
	private UserService userService;
	@Autowired
	private GroupDao groupDao;
	
	@NotNull
	@Size(min = 1, max = 50)
	private String username;
	@NotNull
	@Size(min = 1, max=50)
	private String password;
	@NotNull
	@Size(min = 1, max=50)
	private String passwordRetry;
	
	private List<String> authorities;
	
	private List<String> selectedAuthorities;
	
	private List<Group> groups;
	
	private List<Group> selectedGroups;
	
	@PostConstruct  
	public void init() {
		authorities = new ArrayList<String>();
		for(ApplicationRoles role : ApplicationRoles.values())
			authorities.add(role.name());
		
		clearData();  
	} 
	
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	public String getPasswordRetry() {
		return passwordRetry;
	}
	public void setPasswordRetry(String passwordRetry) {
		this.passwordRetry = passwordRetry;
	}

	public void clearData() {
		this.username = null;
		this.password = null;
		this.passwordRetry = null;
		this.selectedAuthorities = null;
		this.selectedGroups = null;
		try {
			groups = groupDao.findAll();
		} catch (DaoException e) {
		}
	}
	
	@AssertTrue(message="{ar.com.greensoft.PasswordDoNotMatch.message}")
	public boolean isPasswordMatch(){
		if(password == null || passwordRetry == null)
			return false;
		return password.equals(passwordRetry);
	}
	
	public String createUser(){
		if(logger.isTraceEnabled())
			logger.trace("Creating User: " + username);
		
		User user = userService.createUser(username, password);
		
		if(user != null){
			for(String authorityName : selectedAuthorities){
				Authority authority = new Authority();
				authority.setUser(user);
				authority.setAuthority(authorityName);
				userService.grantAuthority(authority);
			}
			user = userService.findUserByUsername(user.getUsername());
		}
		
		if(logger.isTraceEnabled())
			logger.trace("User " + username + " CREATED.");
		
		if(persistReturnView != null && !persistReturnView.isEmpty())
			return persistReturnView + JSFMenuUtil.JSF_REDIRECT;
		return showCreate();
	}
	
	public List<String> getAuthorities() {
		return authorities;
	}

	public void setAuthorities(List<String> authorities) {
		this.authorities = authorities;
	}

	public List<String> getSelectedAuthorities() {
		return selectedAuthorities;
	}

	public void setSelectedAuthorities(List<String> selectedAuthorities) {
		this.selectedAuthorities = selectedAuthorities;
	}

	@Override
	protected String menuRole() {
		return ADMIN_PATH;
	}

	@Override
	protected String menuName() {
		return "users";
	}

	public List<Group> getGroups() {
		return groups;
	}

	public void setGroups(List<Group> groups) {
		this.groups = groups;
	}

	public List<Group> getSelectedGroups() {
		return selectedGroups;
	}

	public void setSelectedGroups(List<Group> selectedGroups) {
		this.selectedGroups = selectedGroups;
	}
}
